package cn.peach.hrm.service.impl;

import cn.peach.hrm.constants.BaseConstants;
import cn.peach.hrm.doc.CourseDoc;
import cn.peach.hrm.domain.Course;
import cn.peach.hrm.domain.CourseDetail;
import cn.peach.hrm.domain.CourseMarket;
import cn.peach.hrm.domain.CourseType;
import cn.peach.hrm.dto.CourseAddParamDto;
import cn.peach.hrm.feign.client.CourseESFeignClient;
import cn.peach.hrm.mapper.CourseMapper;
import cn.peach.hrm.service.ICourseDetailService;
import cn.peach.hrm.service.ICourseMarketService;
import cn.peach.hrm.service.ICourseService;
import cn.peach.hrm.service.ICourseTypeService;
import cn.peach.hrm.to.EmailTo;
import cn.peach.hrm.to.MessageTo;
import cn.peach.hrm.to.SMSTo;
import cn.peach.hrm.util.AjaxResult;
import cn.peach.hrm.util.AssertUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.netflix.eureka.registry.Key;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.EntityMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.validation.Valid;
import java.util.Arrays;
import java.util.Date;

import static cn.peach.hrm.constants.MQConstants.EXCHANGE_NAME_TOPIC;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author peach.ja
 * @since 2021-11-26
 */
@Service
@Transactional
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private ICourseDetailService courseDetailService;

    @Autowired
    private ICourseMarketService courseMarketService;

    @Autowired
    private ICourseTypeService courseTypeService;

    @Autowired
    private CourseESFeignClient courseESFeignClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void save(CourseAddParamDto dto) {
        Course course = dto.getCourse();
        CourseDetail courseDetail = dto.getCourseDetail();
        CourseMarket courseMarket = dto.getCourseMarket();

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq("name", course.getName());
        Course one = super.selectOne(wrapper);
        AssertUtil.isNull(course,"课程名已经存在");

        course.setStatus(BaseConstants.Course.STATUS_OFF_LINE);
        // TODO
        course.setUserId(1L);
        course.setUserName("yhptest1");
        course.setTenantId(26L);
        course.setTenantName("源码时代");
        course.setCommentCount(0);
        course.setSaleCount(0);
        course.setViewCount(0);
        super.insert(course);
        // 保存营销
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);
        // 保存详情
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);

        CourseType courseType = courseTypeService.selectById(course.getCourseTypeId());
        String[] typeIdStrs = courseType.getPath().split("\\.");
        courseTypeService.addTotalCountBuIds(1,typeIdStrs);

    }

    /**
     * 课程上架
     * @param id
     */
    @Override
    public void onLineCourse(Long id) {
        // 根据id查询课程
        Course course = super.selectById(id);
        // 判断状态必须是下架
        AssertUtil.isNotState(course.getStatus(),BaseConstants.Course.STATUS_OFF_LINE,"已经是上架状态了哦");
        // 修改课程状态
        course.setStatus(BaseConstants.Course.STATUS_ON_LINE);
        // 上线时间
        course.setOnlineTime(new Date());
        // 更新数据库的状态
        super.updateById(course);
        // 把课程保存到ES中
        CourseMarket courseMarket = courseMarketService.selectById(id);

        CourseDoc doc = new CourseDoc();
        BeanUtils.copyProperties(courseMarket, doc);
        BeanUtils.copyProperties(course, doc);
        // 收费
        doc.setChargeName(courseMarket.getCharge() == 2? "收费" : "免费");
        AjaxResult result = courseESFeignClient.save(doc);
        AssertUtil.isTrue(result.isSuccess(),"课程发布失败");
        // 发布课程消息
        publishMessage(course);
    }

    //SPEL
    @Value("${message.content.sms.course-publish}")
    public String smsContent;

    @Value("${message.content.email.course-publish}")
    public String emailContent;

    @Value("${message.content.message.course-publish}")
    public String messageContent;

    public void publishMessage(Course course){

        // 发送短信
        smsContent = String.format(smsContent,course.getName() );

        rabbitTemplate.convertAndSend(EXCHANGE_NAME_TOPIC,"course.sms" ,
                new SMSTo(Arrays.asList("11111","11111") ,smsContent));

        // 发送邮件
        emailContent = String.format(emailContent,course.getName() );

        rabbitTemplate.convertAndSend(EXCHANGE_NAME_TOPIC,"course.email" ,
                new EmailTo(Arrays.asList("12333@qq.com","12333@qq.com"),"课程发布了" ,emailContent));

        //发邮件
        messageContent = String.format(messageContent,course.getName() );

        rabbitTemplate.convertAndSend(EXCHANGE_NAME_TOPIC,"course.message" ,
                new MessageTo(Arrays.asList(1L,2L),"课程发布了" ,messageContent));
    }
}
